# -*- coding: utf8 -*-
#
# Copyright (c) 2009 Matías Ribecky <mail@mribecky.com.ar>
#
# This file is part of twitter-notifications.
# 
# twitter-notifications is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# twitter-notifications is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with twitter-notifications.  If not, see <http://www.gnu.org/licenses/>.


'''Cache related functions.'''

import os
import shutil
import urllib2
import logging
import urlparse

import xdg.BaseDirectory

LOGGER = logging.getLogger('twitternotifications.cache')

CACHE_DIR = os.path.join(xdg.BaseDirectory.xdg_cache_home,
                         'twitter-notification',
                         )
USER_IMG_DIR = os.path.join(CACHE_DIR, 'user-images')
if not os.path.exists(CACHE_DIR):
    os.mkdir(CACHE_DIR)
if not os.path.exists(USER_IMG_DIR):
    os.mkdir(USER_IMG_DIR)

def get_user_image(user_name, url):
    '''Retrieve a user image from the url.

    Downloads the user image if not already downloaded and returns the local
    path to it.

    '''

    _, ext = os.path.splitext(urlparse.urlparse(url).path)
    file_name = os.path.join(USER_IMG_DIR, user_name + ext)

    if not os.path.exists(file_name):
        LOGGER.info("Downloading the user image of '%s'" % user_name)

        img_src = urllib2.urlopen(url)
        img_dst = open(file_name, 'wb')

        shutil.copyfileobj(img_src, img_dst)

    return file_name

